package com.appkubes.mall.restful.application.wx.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.appkubes.common.utils.net.HttpClientUtils;
import com.appkubes.mall.restful.application.wx.model.AccessTokenModel;
import com.appkubes.mall.restful.application.wx.model.WxModel;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class WxService {

    @Autowired
    private WxModel wxModel;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取accessToken
     * @return
     * @throws Exception
     */
    public String getAccessToken() throws Exception{
        String accessToken = redisTemplate.opsForValue().get("accessToken");
        if(!StringUtils.isEmpty(accessToken)) return  accessToken;
        String url = wxModel.getWxApiUrl()+"&appid="+wxModel.getAppId()+"&secret="+wxModel.getAppSecret();
        Response response = HttpClientUtils.get(url);
        AccessTokenModel model = JSON.parseObject(response.body().string(), AccessTokenModel.class);
        redisTemplate.opsForValue().set("accessToken",model.getAccess_token(),7200, TimeUnit.SECONDS);
        return model.getAccess_token();
    }

    /**
     * 尝试通过code直接登录配送小程序
     * @return
     * @throws Exception
     */
    public JSONObject getMiniAccessToken(String code) throws Exception{
        String accessTokenUrl = wxModel.getWxMiniCodeUrl()+"appid="+wxModel.getDeliveryAppid()+"&secret="+wxModel.getDeliveryAppsecret()+"&js_code="+code+"&grant_type=authorization_code";
        Response response = HttpClientUtils.get(accessTokenUrl);
        String str = response.body().string();
        if(!StringUtils.isEmpty(str)){
            return JSON.parseObject(str);
            //jsonObj.getString("");
        }
        return null;

    }
}
